package com.lk.socket.config;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/websocket/{sid}")
@Component
public class MyWebsocket {
	
	Logger logger = LoggerFactory.getLogger(this.getClass());

	 //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
            	logger.debug("remote:" + message);
                session.getBasicRemote().sendText(message);
            }
        }else {
        	logger.debug("remote: fail[无session]");
        }
    }
    //给指定用户发送信息
    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
        	logger.debug("正式发送给用户["+userName+"]数据[" + message + "]");
            sendMessage(session, message);
        }catch (Exception e){
        	logger.debug("正式发送消息异常：", e);
            e.printStackTrace();
        }
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
    	sessionPools.put(userName, session);
    	logger.debug("连接成功");
        addOnlineCount();
        logger.debug(userName + "加入webSocket！当前人数为" + onlineNum);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
    	sessionPools.remove(userName);
    	subOnlineCount();
    	logger.debug(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
//    	message = "客户端：" + message + ",已收到";
    	logger.debug(message);
        for (Session session: sessionPools.values()) {
            try {
            	logger.debug("服务器收到用户["+session+"]的消息：["+message+"]");
            	//TODO 根据业务需要把相关信息发送给用户
                //sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
    	logger.debug("发生错误");
        error.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    
}